15. PID List
getPIDList()
9# Example - Class ProcessParser - GetPidList - Part 1
9# Example - Class ProcessParser - GetPidList - Part 2
In this function we open the proc directory and search through every folder, looking for process IDs (PIDs).
If the folder name is in the form of an integer, then we treat this number as an active PID. From this folder we collect data for our process list. Every valid directory with an integer name is pushed onto the vector of process IDs. This vector contains the IDs of the processes running on our machine.
vector<string> ProcessParser::getPidList()
{
DIR* dir;
// Basically, we are scanning /proc dir for all directories with numbers as their names
// If we get valid check we store dir names in vector as list of machine pids
vector<string> container;
if(!(dir = opendir("/proc")))
throw std::runtime_error(std::strerror(errno));
while (dirent* dirp = readdir(dir)) {
// is this a directory?
if(dirp->d_type != DT_DIR)
continue;
// Is every character of the name a digit?
if (all_of(dirp->d_name, dirp->d_name + std::strlen(dirp->d_name), [](char c){ return std::isdigit(c); })) {
container.push_back(dirp->d_name);
}
}
//Validating process of directory closing
if(closedir(dir))
throw std::runtime_error(std::strerror(errno));
return container;
}